<template>
  <div class="wrap">
    <div class="title">
      <img src="../../images/main/store.png" alt> 门店管理
    </div>
    <div class="continer">
      <h1 class="home_sit_bg">房间设置</h1>
      <div class="section" v-for="(item,index) in list" :key="index">
        <div class="xian"></div>
        <div class="left_box">
          <form action method="GET" class="form_ab_house">
            <div for>
              <input class="checkroom" type="checkbox" v-model="item.change" name id>
              <a class="text_nm">
                <img class="red" src="../../images/main/red.png" alt>
                房间{{index + 1}}类型：
              </a>
              <input
                name="roomType"
                v-validate="'required'"
                type="text"
                maxlength="10"
                :placeholder="item.oldRoomType===''?'请选择右方房间类型':'请输入房间类型'"
                class="first_ip"
                v-model="item.roomType"
              >
            </div>
            <span v-show="errorBags.has('roomType')" class="info">请先输入房间类型</span>
            <!-- <span class="info" v-if="!item.roomType">请先输入房间类型</span>
            <span class="info" v-else></span>-->
            <div class="label" >
              <a class="text_nm">
                <img class="red" src="../../images/main/red.png" alt>房间面积：
              </a>
              <input
                name="roomArea"
                v-validate="'required|numeric'"
                placeholder
                type="tel"
                @input="inputRoomArea( item )"
                class="next_ip"
                v-model="item.roomArea"
              >
              <div class="blue_part">约/平米</div>
            </div>
            <span v-show="errorBags.has('roomArea')" class="info">请先输入房间面积</span>
            <!-- <span class="info" v-if="!item.roomArea">请先输入房间面积</span>
            <span class="info" v-else></span>-->
            <div class="label"  for>
              <a class="text_nm">
                <img class="red" src="../../images/main/red.png" alt>建议容纳人数：
              </a>
              
              <input
                name="roomAccommodate"
                v-validate="'required|numeric'"
                placeholder
                class="next_ip"
                type="tel"
                @input="inputRoomAccommodate(item)"
                v-model="item.roomAccommodate"
              >
              <div class="blue_part">人</div>
            </div>
            <span v-show="errorBags.has('roomAccommodate')" class="info">请先输入建议容纳人数</span>
            <!-- <span class="info" v-if="!item.roomAccommodate">请先输入建议容纳人数</span> -->
            <!-- <span class="info" v-else></span> -->
            <div class="label"  style="min-height:300px;">
              <a class="text_nm">
                <img class="red" src="../../images/main/red.png" alt>上传房间照片：
              </a>
              <img class="pl_photo" :src="item.roomImg || require('../../images/main/room.png')">
            </div>
            <div v-if="!item.roomImg" class="red_tips"></div>
            <!-- <span class="info" v-if="!item.roomImg">请上传房间照片</span>
            <span class="info" v-else></span>-->
            <div class="label" >
              <a class="text_nm">
                <img class="red" src="../../images/main/red.png" alt>营业时间：
              </a>
              <!-- <el-checkbox-group></el-checkbox-group> -->
              <el-checkbox
                :style="{
                    display: 'inline-block',
                    paddingRight: '20px',
                    margin: '0px'
                  }"
                v-for="( i ) in item.hours"
                v-model="i.selected"
                :key="i.name"
              >{{ i.label }}</el-checkbox>
            </div>
          </form>
        </div>

        <div class="right_box">
          <!-- <div class="three_box">儿童乐园</div>
          <div class="three_box">绘本区</div>
          <div class="three_box">共享教室</div>-->
          <el-button type="success" @click="shotcut( item, '儿童乐园' )">儿童乐园</el-button>
          <el-button type="primary" @click="shotcut( item, '绘本区' )">绘本区</el-button>
          <el-button type="warning" @click="shotcut( item, '共享教室' )">共享教室</el-button>

          <div class="tips_wx">温馨提示：
            <br>建议上传尺寸为960*675，大小不超过4M,jpg或png格式。
          </div>

          <!-- <div class="cli_part">点击上传</div> -->
          <div style="margin-top:80px;">
            <el-upload
              class="el-upload"
              :action="`${$store.state.baseUrl}/backstage/api/tPartner/upload`"
              :show-file-list="false"
              :auto="true"
              :on-success="(function () {
                return function ( response, file ) {
                  elUploadSuccess( response, file, item );
                }
              })()"
              :before-upload="elUploadBefore"
            >
              <el-button size="small" type="primary" v-if="item.roomImg===''">点击上传</el-button>
              <el-button size="small" type="primary" v-else>修改图片</el-button>
            </el-upload>
          </div>
        </div>
      </div>
      <div class="btn">
        <div @click="addRoom()">增加房间</div>
        <div @click="delRoom()">删除房间</div>
        <div @click="saveRoom()">保存</div>
        <div @click="goBack()">返回</div>
      </div>
    </div>
  </div>
</template>
<script>
import Global from "../tool/Global.vue";
import axios from "axios";
import qs from "qs"; // 将请求转换成form 表单提交形式
const _baseList = [
  {
    roomType: "",
    oldRoomType: "",
    roomArea: "",
    roomImg: "",
    businessHours: "",
    roomAccommodate: "",
    // storeId: '',
    partnerId: this.partnerId,
    hoursCheck: "",
    hours: [
      {
        label: "周一",
        selected: false
      },
      {
        label: "周二",
        selected: false
      },
      {
        label: "周三",
        selected: false
      },
      {
        label: "周四",
        selected: false
      },
      {
        label: "周五",
        selected: false
      },
      {
        label: "周六",
        selected: false
      },
      {
        label: "周日",
        selected: false
      }
    ],
    changeRoom: false
  }
];
export default {
  created() {
    if (this.$route.query.storeId) {
      axios
        .post(
          `${this.$store.state.url}/room/selectByStoreId`,
          qs.stringify({
            storeId: Number(this.$route.query.storeId)
          })
        )
        .then(response => {
          let res = response.data;
          if (res.code == 0) {
            if (res.data) {
              for (let i = 0, len = res.data.length; i < len; i++) {
                let item = res.data[i];
                item.hours = [
                  {
                    label: "周一",
                    selected: false
                  },
                  {
                    label: "周二",
                    selected: false
                  },
                  {
                    label: "周三",
                    selected: false
                  },
                  {
                    label: "周四",
                    selected: false
                  },
                  {
                    label: "周五",
                    selected: false
                  },
                  {
                    label: "周六",
                    selected: false
                  },
                  {
                    label: "周日",
                    selected: false
                  }
                ];

                let arr = item.businessHours.split(",");
                for (let j = 0, len = item.hours.length; j < len; j++) {
                  let jItem = item.hours[j];
                  jItem.selected = arr[j] == "1" ? true : false;
                }
              }
              this.list = res.data;
              for (let index = 0; index < this.list.length; index++) {
                this.list[index].oldRoomType = this.list[index].roomType;
              }
              this.isEdit = true;
              this.isAdd = false;
            }
          }
        });
    } else {
      if (
        this.$route.query.tempRoomList &&
        this.$route.query.tempRoomList.length > 0
      ) {
        this.list = this.$route.query.tempRoomList;
      }
      // sessionStorage.removeItem('roomTempData')
      // let roomDataStr = sessionStorage.getItem('roomTempData')
      // if(roomDataStr){
      //   this.list = JSON.parse(roomDataStr)
      // }
    }
  },
  data() {
    return {
      list: [
        {
          roomType: "",
          oldRoomType: "",
          roomArea: "",
          roomImg: "",
          businessHours: "",
          roomAccommodate: "",
          // storeId: '',
          partnerId: this.partnerId,
          hoursCheck: "",
          hours: [
            {
              label: "周一",
              selected: false
            },
            {
              label: "周二",
              selected: false
            },
            {
              label: "周三",
              selected: false
            },
            {
              label: "周四",
              selected: false
            },
            {
              label: "周五",
              selected: false
            },
            {
              label: "周六",
              selected: false
            },
            {
              label: "周日",
              selected: false
            }
          ],
          changeRoom: false
        }
      ],
      imageUrl: "",
      times: {},
      roomStr: [],
      isEdit: false,
      isAdd: true
    };
  },
  computed: {
    partnerId() {
      return this.$store.state.partnerId;
    }
  },
  watch: {
    // list: {
    //   deep: true,
    //   handler ( val ) {
    //     for ( let i = 0, len = val.length; i < len; i ++ ) {
    //       let item = val[i];
    //       item.businessHours = '';
    //       for ( let j = 0; j < 7; j ++ ) {
    //         if ( j == item.hoursCheck ) {
    //           item.businessHours += 1;
    //         }
    //         if ( j != 6 ) {
    //           item.businessHours += ',';
    //         }
    //       }
    //     }
    //   }
    // }
  },
  methods: {
    getLocalRoomList() {
      let _list = [];
      for (let index = 0; index < this.list.length; index++) {
        const element = this.list[index];
        if (element.id) {
          _list.push(element);
        }
      }
      return _list;
    },
    goBack() {
      this.$route.query.tempRoomList = this.getLocalRoomList();
      this.$router.push({
        path: "/main/editStore",
        query: this.$route.query
      });
      // this.$confirm('返回操作将丢失未保存的房间数据，是否继续?', '提示', {
      //   confirmButtonText: '确定',
      //   cancelButtonText: '取消',
      //   type: 'warning'
      // }).then(() => {
      //   // this.$route.query.roomId = this.$route.query.roomId;

      // }).catch(() => {
      //   this.$message({
      //     type: 'info',
      //     message: '已取消返回'
      //   });
      // });
    },
    inputRoomAccommodate(argv) {
      argv.roomAccommodate = argv.roomAccommodate.replace(/[^0-9]/ig,"")
        if (argv.roomAccommodate < 1 && argv.roomAccommodate!= '') {
          argv.roomAccommodate = 1;
        } else if (argv.roomAccommodate > 9999) {
          argv.roomAccommodate = 9999;
        }
    },
    inputRoomArea(argv) {
      argv.roomArea = argv.roomArea.replace(/[^0-9]/ig,"")
      if (argv.roomArea < 1 && argv.roomArea!= '') {
          argv.roomArea = 1;
        } else if (argv.roomArea > 9999) {
          argv.roomArea = 9999;
        }
    },
    /**
     *  获取房间数量
     */
    shotcut(item, val) {
      item.roomType = val;
    },
    getRoomList: function() {
      let that = this;
      axios({
        method: "post",
        url: `${that.$store.state.url}/room/selectByStoreId`,
        data: qs.stringify({ storeId: Global.storeId })
      }).then(res => {
        if (res.data.code == 0) {
          res.data.data.map(val => {
            val.businessHours = val.businessHours.split(",");
          });

          if (res.data.data.length > 0) {
            that.list = res.data.data;
            that.isEdit = true;
          }
        }
      });
    },
    /**
     * 增加房间
     */

    addRoom: function() {
      let that = this;
      let obj = {
        roomType: "",
        roomArea: "",
        roomImg: "",
        businessHours: "",
        roomAccommodate: "",
        // storeId: '',
        partnerId: this.partnerId,
        hoursCheck: "",
        hours: [
          {
            label: "周一",
            selected: false
          },
          {
            label: "周二",
            selected: false
          },
          {
            label: "周三",
            selected: false
          },
          {
            label: "周四",
            selected: false
          },
          {
            label: "周五",
            selected: false
          },
          {
            label: "周六",
            selected: false
          },
          {
            label: "周日",
            selected: false
          }
        ]
      };
      if (this.$route.query.storeId) {
        obj.storeId = this.$route.query.storeId;
      }
      this.list.push(obj);
      // this.isEdit = false
      this.isAdd = true;
    },
    /**
     * 删除房间
     */
    delRoom: function() {
      let that = this;
      let bol = false
      if (that.list.length == 1) {
            that.$alert("不能删除默认房间!");
            return false;
          }
          that.list.map((val, index) => {
            if (val.change) {
              bol = true;
            }
          });
          if (!bol) {
            that.$alert("请选择房间!");
            return
          }
      this.$confirm("是否确定删除此房间?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          
          let i = this.list.length;
          let bol = false;
          
          while (i--) {
            if (this.list[i].change) {
              if (this.list[i].id) {
                axios
                  .post(
                    `${this.$store.state.url}/room/delRoom `,
                    qs.stringify({ id: this.list[i].id })
                  )
                  .then(response => {
                    let res = response.data;
                    if (res.code == 0) {
                    }
                  });
              }
              this.list.splice(i, 1);
            }
          }
          // sessionStorage.setItem('roomTempData',JSON.stringify(this.list))
          this.$message({
            type: "success",
            message: "删除成功!"
          });
        })
        .then(() => {
          console.log(this.list.length);
          if (this.list.length < 1) {
            this.list = _baseList;
          }
          return;
        })
        .catch(() => {
          // this.$message({
          //   type: 'info',
          //   message: '已取消删除'
          // });
        });
    },
    /**
     * 保存
     */
    saveRoom: function() {
      this.$validator.validate().then(result => {
        if (!result) {
          // do stuff if not valid.
        } else {
          if (this.isAdd) {
            console.log("添加房间");
            this.saveAddRoom();
          } else {
            console.log("编辑房间");
            this.saveEditRoom();
          }
        }
      });
    },
    saveAddRoom: function() {
      let _this = this;
      let bol = false;
      let bols = true;
      for (let i = 0, len = this.list.length; i < len; i++) {
        let item = this.list[i];
        item.businessHours = "";
        for (let j = 0; j < item.hours.length; j++) {
          if (item.hours[j].selected) {
            bol = true;
            item.businessHours += "1";
          } else {
            item.businessHours += "0";
          }
          if (j != 6) {
            item.businessHours += ",";
          }
        }
      }

      let p = [];
      let addIndex = [];
      for (let i = 0, len = this.list.length; i < len; i++) {
        let item = this.list[i];
        let obj = {};
        if (item.id) {
          continue;
        }
        for (let j in item) {
          if (j != "hoursCheck" && j != "hours") {
            obj[j] = item[j];
          }
          // if (!item[j] && j != "hoursCheck") {
          //   return;
          // }
        }
        if (
          !item.roomType ||
          !item.roomAccommodate ||
          !item.roomArea ||
          item.roomImg == require("../../images/main/room.png")
        ) {
          bols = false;
        }
        p.push(obj);
        addIndex.push(i);
      }
      let uploadFlag = true;
      for (let i = 0, len = this.list.length; i < len; i++) {
        if (this.list[i].roomImg === "") {
          uploadFlag = false;
          break;
        }
      }

      let str = JSON.stringify(p);
      // sessionStorage.setItem('roomTempData',JSON.stringify(this.list))
      let data = {
        roomJson: str
      };
      if (!bols) {
        return;
      }
      console.log(uploadFlag);
      if (!uploadFlag) {
        this.$alert("请上传房间图片");
        return false;
      }
      if (!bol) {
        this.$alert("请选择营业时间");
        return false;
      }
      axios
        .post(`${this.$store.state.url}/room/addRoom`, qs.stringify(data))
        .then(response => {
          let res = response.data;
          if (res.code == 0) {
            let str = "";
            let i = 0;
            res.data.forEach((item, index) => {
              this.list[addIndex[i]].id = item;
              this.roomStr.push(item);
              i++;
            });
            this.$route.query.roomId = this.roomStr.toString();
            this.$route.query.tempRoomList = this.list;
            if (this.isEdit) {
              this.saveEditRoom();
            } else {
              this.$store.state.fn.success(res.msg).then(() => {
                this.$router.push({
                  path: "/main/editStore",
                  query: this.$route.query
                });
              });
            }
          }
        });
    },
    saveEditRoom: function() {
      let _this = this;
      let bol = true;
      let roomC = false;
      // 编辑房间
      for (let i = 0, len = this.list.length; i < len; i++) {
        let item = this.list[i];
        item.businessHours = "";
        let bols = false;
        for (let j = 0; j < item.hours.length; j++) {
          if (item.hours[j].selected) {
            bols = true;
            item.businessHours += "1";
          } else {
            item.businessHours += "0";
          }
          if (j != 6) {
            item.businessHours += ",";
          }
        }
        if (!bols) {
          roomC = true;
        }
      }
      // 这里导致无法保存
      let arr_modify = [];
      for (let i = 0, len = this.list.length; i < len; i++) {
        let item = this.list[i];
        let obj = {};
        if (!item.id) {
          continue;
        }
        console.log(item.roomType, "333");
        for (let j in item) {
          if (j != "hoursCheck" && j != "hours") {
            obj[j] = item[j];
          }
          // if (!item[j] && j != "hoursCheck") {
          //   return;
          // }
        }
        if (!item.roomType || !item.roomAccommodate || !item.roomArea) {
          bol = false;
        }
        arr_modify.push(obj);
      }
      let uploadFlag = true;
      for (let i = 0, len = this.list.length; i < len; i++) {
        if (this.list[i].roomImg === "") {
          uploadFlag = false;
          break;
        }
      }
      var str_modify = JSON.stringify(arr_modify);
      var dataModify = {
        roomJson: str_modify
      };
      if (!bol) {
        return;
      }
      console.log(uploadFlag);
      if (!uploadFlag) {
        this.$alert("请上传房间图片");
        return false;
      }
      if (roomC) {
        this.$alert("请选择营业时间!");
        return;
      }
      axios
        .post(
          `${this.$store.state.url}/room/updateRoom`,
          qs.stringify(dataModify)
        )
        .then(response => {
          let res = response.data;
          if (res.code == 0) {
            let str = "";
            res.data.forEach((item, index) => {
              _this.roomStr.push(item);
            });
            this.$route.query.roomId = this.roomStr.toString();

            this.$store.state.fn.success(res.msg).then(() => {
              this.$router.push({
                path: "/main/editStore",
                query: this.$route.query
              });
            });
          }
        });
    },
    elUploadSuccess(response, file, item) {
      // item.roomImg = URL.createObjectURL(file.raw);
      // console.log ( param, file );
      console.log(response);
      if (response.code == 0) {
        item.roomImg = response.data.src;
        this.$alert("上传成功");
      }
    },
    elUploadBefore(file) {
      console.log(file.type.search("image/"));
      const isImg = file.type.search("image/") == -1;
      const isLt8M = file.size / 1024 / 1024 < 8;

      if (isImg) {
        this.$message.error("请上传图片类型!");
      }
      if (!isLt8M) {
        this.$message.error("图片大小不能超过 8MB!");
      }
      return !isImg && isLt8M;
    }
  },
  mounted() {
    // this.getRoomList()
  }
};
</script>
<style scoped lang="scss">
form {
  padding-top: 26px;
}
.info {
  padding-left: 300px;
  color: red;
  font-size: 12px;
  line-height: 24px;
}
.btn {
  height: 55px;
  text-align: center;
  margin-bottom: 107px;
}
.btn > div {
  width: 200px;
  line-height: 55px;
  height: 55px;
  background: #4B74FF;
  font-size: 18px;
  color: #ffffff;
  text-align: center;
  font-weight: bold;
  margin-left: 63px;
  display: inline-block;
  cursor: pointer;
}
.btn > div:first-of-type {
  margin-left: 0;
}
.wrap {
  // padding: 68px 136px;
  width: 90%;
  margin: 40px auto;
}
.title {
  height: 33px;
  line-height: 33px;
  font-size: 24px;
  font-family: PingFangSC-Medium;
  font-weight: bold;
  margin-bottom: 42px;
  width: 1240px;
  margin: 20px auto;
}
.title img {
  width: 28px;
  height: 26px;
  float: left;
  padding-top: 5px;
  margin-right: 10px;
}
.continer {
  background: #ffffff;
  box-shadow: 0 5px 20px 0 rgba(0, 0, 0, 0.05);
  border-radius: 6px;
  width: 100%;
  // width: 1475px;
  /* height: 2535px; */
  display: inline-block;
  // margin-left: 48px;
  width: 1200px;
  margin: 20px auto;
}
.home_sit_bg {
  line-height: 100px;
  width: 300px;
  margin-left: 95px;
  font-family: PingFangSC-Medium;
  font-size: 24px;
  color: #000000;
  font-weight: bold;
}
.section {
  width: 100%;
  overflow: hidden;
  display: block;
  min-height: 550px;
}
.xian {
  background: #f5f5f5;
  width: 1423px;
  height: 3px;
  margin: 0 auto;
}
.left_box {
  float: left;

  text-align: left;
  font-family: PingFangSC-Medium;
  font-size: 18px;
  color: #000000;
  letter-spacing: 0.02px;
  text-align: left;
  padding-bottom: 39px;
}
.checkroom {
  background: #1989fa;
  border-radius: 2px;
  width: 25px;
  height: 25px;
  float: left;
  margin-left: 25px;
  margin-right: 45px;
  margin-top: 7px;
}
.form_ab_house label:first-child {
  margin-left: 0px;
}
.text_nm {
  font-family: PingFangSC-Medium;
  font-size: 18px;
  color: #000000;
  height: 40px;
  line-height: 40px;
  font-weight: bold;
  width: 196px;
  display: inline-block;
}
.first_ip {
  background: #ffffff;
  box-shadow: inset 0 1px 3px 0 rgba(0, 0, 0, 0.5);
  width: 317px;
  height: 40px;
  padding-left: 10px;
  box-sizing: border-box;
  font-size: 18px;
  color: #888888;
}
.next_ip {
  background: #ffffff;
  box-shadow: inset 0 1px 3px 0 rgba(0, 0, 0, 0.5);
  width: 230px;
  height: 40px;
  padding: 0 10px;
  margin: 0;
  float: left;
  box-sizing: border-box;
  font-size: 18px;
  color: #888888;
}
.form_ab_house .label {
  margin: 15px 0 0 95px;
  padding: 0;
  display: block;
  overflow: hidden;
}
.form_ab_house .label a {
  display: block;
  width: 200px;
  float: left;
}
.pl_photo {
  width: 320px;
  // height: 205px;
}
.blue_part {
  background: #4B74FF;
  border: 1px solid #979797;
  width: 87px;
  height: 38px;
  color: #ffffff;
  margin-left: 0;
  text-align: center;
  line-height: 42px;
  vertical-align: bottom;
  float: left;
  font-size: 18px;
  color: #ffffff;
  margin-left: -2px;
  margin-top: -1px;
}
.input_box {
  width: 400px;
  height: 40px;
  display: inline-block;
}
.red_tips {
  font-family: PingFangSC-Medium;
  font-size: 18px;
  color: #da260e;
  letter-spacing: 0;
  text-align: left;
  margin-left: 355px;
  line-height: 88px;
  font-weight: bold;
}
.red {
  width: 10px;
  height: 10px;
  padding: 15px 5px;
  float: left;
}
.check_part {
  margin-left: 20px;
  background: #ffffff;
  border: 1px solid #979797;
  width: 18px;
  height: 18px;
  display: inline-block;
  vertical-align: middle;
}
.check_part:first-of-type {
  margin-left: 0;
}
.right_box {
  float: left;

  margin-top: 39px;
  text-align: left;
  font-family: PingFangSC-Medium;
  font-size: 18px;
  color: #000000;
  letter-spacing: 0.02px;
  text-align: left;
  overflow: hidden;
  width: 340px;
}
.three_box {
  background: #ffffff;
  border: 1px solid #4B74FF;
  border-radius: 3px;
  width: 114px;
  height: 38px;
  font-family: PingFangSC-Medium;
  font-size: 18px;
  color: #4B74FF;
  letter-spacing: 0.02px;
  text-align: center;
  line-height: 38px;
  margin-right: 36px;
  float: left;
}

.tips_wx {
  height: 75px;
  line-height: 37px;
  font-family: PingFangSC-Medium;
  font-size: 18px;
  color: #888888;
  letter-spacing: 0.03px;
  font-weight: bold;
  clear: left;
  margin-top: 150px;
}
.upload {
  .el-upload {
    width: 100px;
    height: 100px;
    border: 1px dashed #ddd;
    line-height: 100px;
    /deep/ .el-upload {
      width: 100%;
    }
  }
  padding-top: 60px;
}
.cli_part {
  background: #4B74FF;
  width: 255px;
  height: 55px;
  margin-top: 49px;
  text-align: center;
  line-height: 55px;
  font-family: PingFangSC-Medium;
  font-size: 18px;
  color: #ffffff;
  letter-spacing: 0.03px;
}
</style>
